<template>
    <div>
        <!-- 导航栏 -->
        <van-nav-bar
            title="注册 / 登录"
            left-arrow
            @click-left="$router.back()"
        />
        <!-- 登录表单 -->
        <van-form
            validate-first
            :show-error="false"
            :show-error-message="false"
            ref="formRef"
            @submit="onLogin"
            @failed="onFalied"
        >
            <van-field
                v-model="user.mobile"
                clearable
                center
                icon-prefix="iconfont"
                left-icon="shouji"
                placeholder="请输入手机号码"
                name="mobile"
                :rules="formRules.mobile"
            />
            <van-field
                v-model="user.code"
                clearable
                center
                icon-prefix="iconfont"
                left-icon="yanzhengma"
                placeholder="请输入验证码"
                name="code"
                :rules="formRules.code"
            >
                <template #button>
                    <van-count-down
                        v-if="isShowCountDown"
                        :time="1000 * 10"
                        format=" ss s"
                        @finish="isShowCountDown = false"
                    />
                    <van-button
                        v-else
                        class="send-btn"
                        size="mini"
                        round
                        :loading="isSendLoading"
                        @click.prevent="onSend"
                        >发送验证码</van-button
                    >
                </template>
            </van-field>
            <div class="login-btn-wrap">
                <van-button class="login-btn" type="info" block
                    >登录</van-button
                >
            </div>
        </van-form>
    </div>
</template>

<script>
import { login, sendMes } from '@/api/user'

export default {
    name: 'loginIndex',
    data () {
        return {
            user: {
                mobile: '17090086870',
                code: '246810'
            },
            formRules: {
                mobile: [
                    { required: true, message: '请输入手机号码' },
                    { pattern: /^1[3|5|7|8]\d{9}$/, message: '手机号码格式错误' }
                ],
                code: [
                    { required: true, message: '请输入验证码' },
                    { pattern: /^\d{6}$/, message: '验证码格式错误' }
                ]
            },
            // 控制倒记时和发送验证码按钮是否显示
            isShowCountDown: false,
            // 控制是否显示加载图标
            isSendLoading: false
        }
    },
    created () { },
    mounted () {
        // 重新添加缓存页面
        this.$store.commit('addCachePages', 'layoutIndex')
    },
    methods: {
        async onLogin () {
            this.$toast.loading({
                message: '登录中...',
                // 禁止背景点击
                forbidClick: true,
                // 展示时长 为 0 不会消失
                duration: 0
            })
            try {
                // const res = await this.$axios.post('/app/v1_0/authorizations', this.user)
                // await this.$axios.post('/app/v1_0/authorizations', this.user)
                const { data: res } = await login(this.user)
                this.$toast.success('登录成功!')
                // console.log(res);
                // 把token 值存到 vuex 中
                this.$store.commit('setUser', res.data)

                // 跳转页面前清除 layoutIndex 缓存
                this.$store.commit('removeCachePages', 'layoutIndex')

                // this.$router.back()
                const redirect = this.$route.query.redirect || '/'
                this.$router.push(redirect)
            } catch {
                this.$toast.fail('登录失败，手机号或验证码错误!')
            }
        },
        // 自定义校验错误信息
        onFalied (error) {
            if (error.errors[0]) {
                this.$toast({
                    message: error.errors[0].message,
                    position: 'top'
                })
            }
        },
        // 获取短信验证码
        async onSend () {
            try {
                // 校验手机号码
                await this.$refs.formRef.validate('mobile')
                this.isSendLoading = true
                // 校验通过，请求发送验证码
                // await this.$axios.get(`/app/v1_0/sms/codes/${this.user.mobile}`)
                await sendMes(this.user.mobile)

                // 显示倒记时，隐藏发送验证码按钮
                this.isShowCountDown = true
            } catch (error) {
                // console.dir(error);
                let message = ''
                if (error.response && error.response.status === 429) {
                    // 发送短信失败的提示
                    message = '发送太频繁了，请稍后再试'
                } else if (error.name === 'mobile') {
                    // 手机号码验证失败的错误提示
                    message = error.message
                    // console.log(error);
                } else {
                    // 未知错误
                    message = '发送失败，请稍后再试'
                }
                this.$toast({
                    message: message,
                    position: 'top'
                })
            }
            this.isSendLoading = false
        }
    }
}
</script>

<style scoped>
.van-nav-bar .van-icon {
    color: #fff;
}
.login-btn-wrap {
    padding: 26px 16px;
}

.login-btn {
    border: none;
    background-color: #6db4fb;
}

.van-button__text {
    font-size: 15px;
}

.send-btn {
    width: 76px;
    height: 23px;
    background-color: #ededed;
}

.send-btn .van-button__text {
    font-size: 11px;
    color: #666666;
}
</style>
